<?php

namespace App\Http\Controllers\Rent\Business;

use App\Http\Controllers\ShopController;
use App\Models\Business\Business as BusinessModel;
use App\Models\Business\Collection as CollectionModel;
use App\Models\Business\Source as SourceModel;
use App\Models\Config as ConfigModel;
use App\Models\Product\Order\Order as OrderModel;
use App\Models\Region as RegionModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class BaseController extends ShopController
{
    public function index()
    {
        $busid = request('busid','');

        $ProductCount = CollectionModel::where([['busid','=',$busid],['proid','<>','']])->count();
        $CateCount = CollectionModel::where([['busid','=',$busid],['cateid','<>','']])->count();
        $OrderCount = OrderModel::where(['busid' => $busid])->count();

        $data = [
            'ProductCount' => $ProductCount,
            'CateCount' => $CateCount,
            'OrderCount' => $OrderCount
        ];

        return $this->success('查询成功',$data);
    }

    public function register()
    {
        $mobile = request('mobile','');
        $password = request('password','');

        // 生成密码盐
        $salt = build_randstr();

        $password = md5($password . $salt);

        // 封装数据
        $data = [
            'mobile' => $mobile,
            'password' => $password,
            'salt' => $salt
        ];

        // 客户来源
        $source = SourceModel::where('name','LIKE','%租赁%')->first();

        if($source)
        {
            $data['sourceid'] = $source['id'];
        }

        // 定义验证器
        $validate = [
            [
                'mobile' => ['required','unique:business','regex:/^1[356789]\d{9}$/'],
                'password' => ['required'],
                'salt' => ['required']
            ],
            [
                'mobile.required' => '手机号必填',
                'mobile.unique' => '手机号已注册',
                'mobile.regex' => '手机号格式错误',
                'password.required' => '密码必填',
                'salt.required' => '密码盐未知',
            ]
        ];

        // 创建验证器
        $validator = Validator::make($data,...$validate);

        if($validator->fails())
        {
           return $this->error($validator->errors()->first());
        }

        $result = BusinessModel::create($data);

        if($result === false)
        {
            return $this->error('注册失败');
        }else{
            return $this->success('注册成功');
        }
    }

    public function login()
    {
        $mobile = request('mobile','');
        $password = request('password','');

        $business = BusinessModel::where(['mobile' => $mobile])->first();

        if(!$business)
        {
            return $this->error('手机号未注册');
        }

        $password = md5($password . $business['salt']);

        if($password !== $business['password'])
        {
            return $this->error('密码错误');
        }

        $data = [
            'id' => $business['id'],
            'mobile' => $business['mobile'],
            'mobile_text' => $business['mobile_text'],
            'nickname' => $business['nickname'],
            'email' => $business['email'],
            'gender' => $business['gender'],
            'gender_text' => $business['gender_text'],
            'province' => $business['province'],
            'city' => $business['city'],
            'district' => $business['district'],
            'region_text' => $business['region_text'],
            'auth' => $business['auth'],
            'avatar_cdn' => $business['avatar_cdn']
        ];

        return $this->success('登录成功',$data);
    }

    public function profile()
    {
        $params = request()->input();

        $business = request()->get('business');

        $data = [
            'nickname' => $params['nickname'],
            'email' => $params['email'],
            'gender' => $params['gender'],
        ];

        if($params['email'] != $business['email'])
        {
            $data['auth'] = '0';
        }

        if(!empty($params['password']))
        {
            $repass = md5($params['password'] . $business['salt']);

            if($repass == $business['password'])
            {
                return $this->error('新密码与原密码一致');
            }

            $salt = build_randstr();

            $data['password'] = md5($params['password'] . $salt);
            $data['salt'] = $salt;
        }

        if(isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0)
        {
            $cdn = ConfigModel::where('name','url')->value('value');

            $url = env('SITE_URL',$cdn);

            $url = $url . '/base/business/upload';

            // 第一个参数属于文件路径 第二个参数是文件类型 第三个是文件名
            $file =  new \CURLFile($_FILES['avatar']['tmp_name'],$_FILES['avatar']['type'],$_FILES['avatar']['name']);
            
            $res = httpRequest($url,['avatar' => $file,'id' => $business['id']]);

            $avatar = json_decode($res,true);
            
            if($avatar['code'] === 0)
            {
                return $this->error($avatar['msg']);
            }

            $data['avatar'] = $avatar['data'];
        }

        // 地区
        $path = RegionModel::where('code',$params['code'])->value('parentpath');

        if(!$path)
        {
            return $this->error('所选地区不存在');
        }

        [$province,$city,$district] = explode(',',$path);

        $data['province'] = $province ?? null;
        $data['city'] = $city ?? null;
        $data['district'] = $district ?? null;

        $result = BusinessModel::where(['id' => $params['busid']])->update($data);

        if($result === false)
        {
            if(isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0)
            {
                $cdn = ConfigModel::where('name','url')->value('value');
                
                $url = env('SITE_URL',$cdn);

                $url = $url . '/base/business/del';

                httpRequest($url,['id' => $business['id'],'avatar' => $data['avatar']]);
            }

            return $this->error('更新资料失败');
        }else{
            if(isset($data['avatar']) && $_FILES['avatar']['size'] > 0)
            {
                $cdn = ConfigModel::where('name','url')->value('value');

                $url = env('SITE_URL',$cdn);

                $url = $url . '/base/business/del';
                
                httpRequest($url,['id' => $business['id'],'avatar' => $business['avatar']]);
            }

            $business = BusinessModel::find($params['busid']);

            $data = [
                'id' => $business['id'],
                'mobile' => $business['mobile'],
                'mobile_text' => $business['mobile_text'],
                'nickname' => $business['nickname'],
                'email' => $business['email'],
                'gender' => $business['gender'],
                'gender_text' => $business['gender_text'],
                'province' => $business['province'],
                'city' => $business['city'],
                'district' => $business['district'],
                'region_text' => $business['region_text'],
                'auth' => $business['auth'],
                'avatar_cdn' => $business['avatar_cdn']
            ];

            return $this->success('更新资料成功',$data);
        }
    }
}
